<template>
	<div class="node-wrap">
		<!-- 节点显示 start -->
		<div class="node-wrap-box" :class="[disabled ? 'node-wrap-box--disabled' : '', `node-wrap-box--${nodeConfig.local_status}`]">
			<div class="title" style="background: #9260fa">
				<el-icon class="icon"><Money /></el-icon>
				<span v-show="!isEditTitle" class="title_label" @click="editTitle('box_nodeTitle')"
					>{{ nodeConfig.nodeName }}<el-icon v-if="!disabled" class="edit-icon"><edit /></el-icon
				></span>
				<el-input
					v-show="isEditTitle"
					ref="box_nodeTitle"
					v-model="nodeConfig.nodeName"
					clearable
					size="small"
					@blur="saveTitle"
					@keyup.enter="saveTitle"
				></el-input>
				<el-icon v-if="!disabled" class="close" @click.stop="delNode()"><close /></el-icon>
			</div>
			<div class="content" @click="show">
				<span v-if="toText(nodeConfig)">{{ toText(nodeConfig) }}</span>
				<span v-else class="placeholder">请选择子流程规则</span>
			</div>
		</div>
		<!-- 节点显示 end -->

		<!-- 添加节点 start -->
		<add-node v-model="nodeConfig.childNode" :disabled="disabled"></add-node>
		<!-- 添加节点 end -->

		<!-- 打开侧边弹窗 start -->
		<el-drawer v-model="drawer" title="子流程设置" destroy-on-close append-to-body :size="600" class="aDrawer">
			<template #header>
				<div class="node-wrap-drawer__title">
					<label v-show="!isEditTitle" @click="editTitle('nodeTitle')"
						>{{ form.nodeName }}<el-icon class="node-wrap-drawer__title-edit"><edit /></el-icon
					></label>
					<el-input v-show="isEditTitle" ref="nodeTitle" v-model="form.nodeName" clearable @blur="saveTitle" @keyup.enter="saveTitle" class="w-40"></el-input>
					<el-input v-model="form.nodeKey" clearable class="w-40 pl-1.5" placeholder="请填写nodeKey"></el-input>
				</div>
			</template>
			<el-container>
				<el-main>
					<div class="self-radio-group">
						<el-radio-group v-model="radio1">
							<el-radio-button v-for="v of subProcessType" :key="v.value" :label="v.value">{{ v.label }}</el-radio-button>
						</el-radio-group>
					</div>

					<!-- 设置子流程 -->
					<div v-show="radio1 === '1'">
						<div class=""><el-text class="mx-1">选择子流程</el-text></div>
						<div>
							<el-select
								v-model="form.subProcessValue"
								placeholder="选择子流程"
								filterable
								remote
								:remote-method="fetchData"
								:loading="loading"
								style="width: 240px; margin: 10px 20px 10px 0px"
								@change="chooseProcess"
							>
								<el-option v-for="item in options" :key="item.id" :label="item.processName" :value="item.id" />
							</el-select>

							<el-link :underline="false" @click="openViewEv"
								><el-icon class="el-icon--right"><View /></el-icon> 预览子流程</el-link
							>
						</div>
					</div>

					<!-- 表单设置 -->
					<div v-show="radio1 === '2'">
						<el-table ref="multipleTableRef" :data="form.extendConfig.formConfig" style="width: 100%" border>
							<el-table-column property="label" label="表单字段" align="center" />
							<el-table-column align="center">
								<template #header>操作权限</template>
								<template #default="scope">
									<el-radio-group v-model="scope.row.opera">
										<el-radio label="0" size="small">只读</el-radio>
										<el-radio label="1" size="small">编辑</el-radio>
										<el-radio label="2" size="small">隐藏</el-radio>
									</el-radio-group>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-main>
				<el-footer>
					<el-button type="primary" @click="save">保存</el-button>
					<el-button @click="drawer = false">取消</el-button>
				</el-footer>
			</el-container>
		</el-drawer>
		<!-- 打开侧边弹窗 end -->
	</div>
</template>

<script>
import addNode from './addNode'
import { subProcessType } from './config'
import { ElMessage } from 'element-plus'
import { mapState } from 'pinia'
import useFlowStore from '@/store/modules/flow'
import process from '@/api/flow/process'

export default {
	components: {
		addNode
	},
	props: {
		modelValue: { type: Object, default: () => {} },
		disabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			nodeConfig: {},
			drawer: false,
			isEditTitle: false,
			form: {},
			radio1: '1',
			subProcessType,
			options: [],
			loading: false,
			processName: ''
		}
	},
	watch: {
		modelValue() {
			this.nodeConfig = this.modelValue
		}
	},
	mounted() {
		this.nodeConfig = this.modelValue
	},
	methods: {
		chooseProcess(e) {
			this.processName = this.options.filter(i => i.id === e)[0].processName
		},
		show() {
			if (this.disabled) return
			this.form = {}
			this.form = JSON.parse(JSON.stringify(this.nodeConfig))
			const { formStructure } = JSON.parse(this.processForm)
			const formConfig = this.form.extendConfig?.formConfig || []
			const operateTable = (formStructure?.fields || []).map(item => {
				let opera = '1'
				formConfig.map(i => {
					if (item.id === i.id) {
						opera = i.opera
					}
				})
				return { label: item.label, id: item.id, opera: opera }
			})
			this.form.extendConfig = { formConfig: operateTable }
			/**
			 * 将后台给的 callProcess 重新组装
			 * 拿着id去获取process值，在塞入子流程下拉列中
			 * @type {*}
			 */
			const newCallProcess = this.form?.callProcess
			if (newCallProcess) {
				const val = newCallProcess.split(':')
				this.form.subProcessValue = val[0]
				this.processName = val[1]
				this.form.callProcess = `${val[0]}:${val[1]}`
				this.getProcessDetail(val[0])
			} else {
				process.childProcessTop10Api({ keyword: '' }).then(res => {
					this.options = res || []
				})
			}
			this.drawer = true
		},
		editTitle(refName) {
			if (this.disabled) return
			this.isEditTitle = true
			this.$nextTick(() => {
				if (this.$refs[refName]) {
					this.$refs[refName].focus()
				}
			})
		},
		saveTitle() {
			this.isEditTitle = false
		},
		save() {
			if (!this.form.nodeKey) {
				return ElMessage.error('请填写nodeKey')
			}
			if (!this.form.subProcessValue) {
				return ElMessage.warning('请设置子流程')
			}
			this.form.callProcess = `${this.form.subProcessValue}:${this.processName}`
			this.$emit('update:modelValue', this.form)
			this.drawer = false
		},
		delNode() {
			this.$emit('update:modelValue', this.nodeConfig.childNode)
		},
		toText(nodeConfig) {
			const { callProcess } = nodeConfig
			if (callProcess) {
				const val = callProcess.split(':')
				return `${val[1]}`
			} else {
				return false
			}
		},
		async fetchData(query) {
			// 如果输入为空，则不调用接口
			if (!query) {
				return
			}
			this.loading = true
			try {
				const data = await process.childProcessTop10Api({ keyword: query })
				this.options = data
				this.loading = false
			} catch (e) {
				this.loading = false
			}
		},
		async getProcessDetail(id) {
			const { processId, processName } = await process.processDetailApi(id)
			this.options = [{ id: processId, processName }]
		},
		openViewEv() {
			const id = this.form.subProcessValue
			if (!id) {
				ElMessage.error('您还没有选择需要预览的子流程')
				return false
			}
			const { origin, hash } = window.location
			const hashFlag = hash.indexOf('#') !== -1 // 路由是hash模式
			const jumpRouterUrl = `${origin}/${hashFlag ? '#' : ''}/flow_create/child?id=${id}`
			window.open(jumpRouterUrl)
		}
	},
	computed: {
		...mapState(useFlowStore, ['processForm']) //映射函数，取出processForm
	}
}
</script>

<style></style>
